import httpStatusNavigateTo from './httpStatusNavigateTo';

const url_all = {
	'development': 'http://127.0.0.1:1000', // 开发
	'production': '' // 线上
}

let BASEURL = url_all[process.env.NODE_ENV];

export const request = (options={}) => {
	return new Promise((resolve,rejects)=>{
        handleRequest(options,resolve,rejects);
	})
}

export const upload = (options={}) => {
	return new Promise((resolve,rejects)=>{
        handleUpload(options,resolve,rejects);
	})
}

// 发起请求
function handleRequest(options, resolve, reject) {
	const store = require('@/store/index');
	const header = {};
	if (store.default.state.token){
		header['Authorization'] = store.default.state.token;
		header['cookie'] = store.default.state.sessionId;
	}
	uni.$tn.message.loading('')
	uni.request({
		url: BASEURL + options.url,
		method: options.method,
		data: options.data,
		header: {
			...header
		},
		withCredentials:true,
		timeout: 1000 * 15,
		success: (response) => {
			uni.$tn.message.closeLoading();
			const token = response.header['Authorization'];
			if (token){
				store.default.commit('$tStore',{
					name: 'token',
					value: token
				});
				store.default.commit('$tStore',{
					name: 'sessionId',
					value: response.header["Set-Cookie"]
				});
			}
			if (!response.data.success){
				uni.$tn.message.toast(response.data.message);
			}
			return resolve(response.data)
		},
		fail: (fail) => {
			uni.$tn.message.closeLoading();
			return reject(fail);
		}
	})
}

// 发起请求
function handleUpload(options, resolve, reject) {
	const store = require('@/store/index');
	const header = {};
	if (store.default.state.token){
		header['Authorization'] = store.default.state.token;
		header['cookie'] = store.default.state.sessionId;
	}
	uni.$tn.message.loading('')
	uni.uploadFile({
		url: BASEURL + options.url,
		filePath: options.filePath,
		name: options.name,
		method: 'GET',
		header:{
			...header
		},
		timeout: 1000 * 15,
		success: (response) => {
			uni.$tn.message.closeLoading();
			if (token){
				store.default.commit('$tStore',{
					name: 'token',
					value: token
				});
				store.default.commit('$tStore',{
					name: 'sessionId',
					value: response.header["Set-Cookie"]
				});
			}
			const reponseBody = JSON.parse(response.data);
			if (!reponseBody.success){
				uni.$tn.message.toast(reponseBody.message);
			}
			httpStatusNavigateTo(reponseBody.code);
			return resolve(response.data)
		},
		fail: (fail) => {
			uni.$tn.message.closeLoading();
			console.log('fail',fail)
			return reject(fail);
		}
	})
}